// ==UserScript==
// @name        League of Legends - Tribunal Helper
// @namespace   LoLTH
// @description Helps with judging cases in the League of Legends Tribunal
// @version     1.1.9
// @grant none
// @include http://na.leagueoflegends.com/tribunal/en/review/
// ==/UserScript==


// Display Initialization

$("#tribunal-case").prepend("<div id='LoLTHController'class='LoLTHController LoLTHRoundMe'><section><div id='LoLTHTitle'class='LoLTHTitle disableSelection pointerFinger'align='center'><i class='fa fa-gavel'style='float: left'></i> Tribunal Helper - Loading Case<i id='LoLTHArrowPointer'class='fa fa-spinner fa-spin'style='float: right'></i></div></section></div>");

var style = "<style type='text/css'>.LoLTHController{position:absolute;left:29%;width:300px;height:20px;padding:5px;margin:2px;font-family:Verdana,Arial,sans-serif;font-size:12px;font-weight:bold;color:#000000;z-index:250000;}.LoLTHTitle{background-image:linear-gradient(to bottom,#428bca 0,#2d6ca2 100%);margin:-5px;border-radius:4px;padding:10px;color:#fff;border:1px solid rgb(43,102,154);} .LoLTHWrapper{position:absolute;width:310px;top:38px;left:0px;border-top-left-radius:4px;border-top-right-radius:4px;border-bottom-right-radius:4px;border-bottom-left-radius:4px;-moz-box-shadow:0px 6px 12px rgba(0,0,0,0.172549);-webkit-box-shadow:0px 6px 12px rgba(0,0,0,0.172549);box-shadow:0px 6px 12px rgba(0,0,0,0.172549);display:none;} .LoLTHHeader{margin:-1px0px0px0px;padding:5px;background-color:#47a447;color:#fff;font-weight:normal;border:1px solid #398439;outline:0} .LoLTHBlock{font-size:10px;font-weight:normal;margin:-6px-6px 5px-6px;} .LoLTHError{font-size:10px;font-weight:normal;color:#CE1C18;} .LoLTHPardon{color:#37BD22;} .LoLTHPunish{color:#CE1C18;} .LoLTHDunno{color:#9B00FE;} .disableSelection{user-select:none;-o-user-select:none;-moz-user-select:none;-khtml-user-select:none;-webkit-user-select:none;}.pointerFinger{cursor:pointer} .LoLTHRoundMe{-webkit-border-radius:8px;-moz-border-radius:8px;border-radius:8px;}</style>";

$("head").append(style);

var link = "<link rel='stylesheet' type='text/css' media='all' href='//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.min.css'>";

$("head").append(link);

var ddinject = "<script type='text/javascript'>rg_force_language = 'en_US'; rg_force_manifest = 'http://gameinfo.na.leagueoflegends.com/assets/js/na.js'; rg_force_reducereflow = true; </script> <script type='text/javascript' src='http://ddragon.leagueoflegends.com/cdn/dragonhead.js'></script>";
$("body").append(ddinject);

var jqueryuiinject = "<script src='http://code.jquery.com/ui/1.10.4/jquery-ui.min.js'></script>";
$("body").append(jqueryuiinject);

// Logic Initialization

var LoLTH = {
	Utility: {},
	Data: {},
	Fetch: {},
	Summary: {},
	Game: {},
	Parse: {},
	Scorer: {},
	Output: {}
};

LoLTH.Data.ReportableOffenses = {
	"Offensive Language" : 3,
	"Verbal Abuse" : 4,
	"Intentional Feeding" : 0.5,
	"Assisting Enemy Team" : 10,
	"Refusing to Communicate" : 10,
	"AFK" : 10,
	"Negative Attitude" : 3,
	"Spamming" : 2
};

// Config
LoLTH.Data.ItemChecks = true; 

// Cache Data

LoLTH.Data.ProfanityList = [ "ahole", "anus", "ashle", "ashles", "asholes", "ass", "Ass Monkey", "Assface", "asshle", "asshlez", "asshole", "assholes", "assholz", "asswipe", "azzhole", "bassterds", "bastard", "bastards", "bastardz", "basterds", "basterdz", "Biatch", "bitch", "bitches", "Blow Job", "boffing", "butthole", "buttwipe", "cck", "ccks", "ck", "Carpet Muncher", "cawk", "cawks", "Clit", "cnts", "cntz", "cock", "cockhead", "cock-head", "cocks", "CockSucker", "cock-sucker", "crap", "cum", "cunt", "cunts", "cuntz", "dick", "dild", "dilds", "dildo", "dildos", "dilld", "dillds", "dominatricks", "dominatrics", "dominatrix", "dyke", "enema", "f u c k", "f u c k e r", "fag", "fagt", "faget", "faggt", "faggit", "faggot", "fagit", "fags", "fagz", "faig", "faigs", "fart", "flipping the bird", "fuck", "fucker", "fuckin", "fucking", "fucks", "Fudge Packer", "fuk", "Fukah", "Fuken", "fuker", "Fukin", "Fukk", "Fukkah", "Fukken", "Fukker", "Fukkin", "gk", "gay", "gayboy", "gaygirl", "gays", "gayz", "God-damned", "hr", "har", "hre", "hells", "hoar", "hoor", "hoore", "jackoff", "jap", "japs", "jerk-off", "jisim", "jiss", "jizm", "jizz", "knob", "knobs", "knobz", "kunt", "kunts", "kuntz", "Lesbian", "Lezzian", "Lipshits", "Lipshitz", "masochist", "masokist", "massterbait", "masstrbait", "masstrbate", "masterbaiter", "masterbate", "masterbates", "Motha Fucker", "Motha Fuker", "Motha Fukkah", "Motha Fukker", "Mother Fucker", "Mother Fukah", "Mother Fuker", "Mother Fukkah", "Mother Fukker", "mother-fucker", "Mutha Fucker", "Mutha Fukah", "Mutha Fuker", "Mutha Fukkah", "Mutha Fukker", "ngr", "nastt", "nigger;", "nigur;", "niiger;", "niigr;", "orafis", "orgasim;", "orgasm", "orgasum", "oriface", "orifice", "orifiss", "packi", "packie", "packy", "paki", "pakie", "paky", "pecker", "peeenus", "peeenusss", "peenus", "peinus", "pens", "penas", "penis", "penis-breath", "penus", "penuus", "Phuc", "Phuck", "Phuk", "Phuker", "Phukker", "polac", "polack", "polak", "Poonani", "prc", "prck", "prk", "pusse", "pussee", "pussy", "puuke", "puuker", "queer", "queers", "queerz", "qweers", "qweerz", "qweir", "recktum", "rectum", "retard", "sadist", "scank", "schlong", "screwing", "semen", "sex", "sexy", "Sh!t", "sht", "shter", "shts", "shtter", "shtz", "shit", "shits", "shitter", "Shitty", "Shity", "shitz", "Shyt", "Shyte", "Shytty", "Shyty", "skanck", "skank", "skankee", "skankey", "skanks", "Skanky", "slut", "sluts", "Slutty", "slutz", "son-of-a-bitch", "tit", "turd", "vajina", "vagna", "vagiina", "vagina", "vajna", "vajina", "vullva", "vulva", "wp", "whr", "whre", "whore", "xrated", "xxx", "b!+ch", "bitch", "blowjob", "clit", "arschloch", "fuck", "shit", "ass", "asshole", "b!tch", "bch", "btch", "bastard", "bi+ch", "boiolas", "buceta", "cck", "cawk", "chink", "cipa", "clits", "cock", "cum", "cunt", "dildo", "dirsa", "ejakulate", "fatass", "fcuk", "fuk", "fuxr", "hoer", "hore", "jism", "kawk", "litch", "li+ch", "lesbian", "masturbate", "masterbat*", "masterbat", "motherfucker", "s.o.b.", "mofo", "nazi", "nigga", "nigger", "nutsack", "phuck", "pimpis", "pusse", "pussy", "scrotum", "sh!t", "shemale", "shi+", "sh!+", "slut", "smut", "teets", "tits", "boobs", "bbs", "teez", "testical", "testicle", "titt", "wse", "jackoff", "wank", "whoar", "whore", "*damn", "*dyke", "*fuck*", "*shit*", "@$$", "amcik", "andskota", "arse*", "assrammer", "ayir", "bich", "bitch*", "bollock*", "breasts", "butt-pirate", "cabron", "cazzo", "chraa", "chuj", "Cock*", "cunt*", "dmn", "daygo", "dego", "dick*", "dike*", "dupa", "dziwka", "ejackulate", "Ekrem*", "Ekto", "enculer", "faen", "fag*", "fanculo", "fanny", "feces", "feg", "Felcher", "ficken", "fitt*", "Flikker", "foreskin", "Fotze", "Fu(*", "fuk*", "futkretzn", "gay", "gook", "guiena", "hr", "hxr", "hell", "helvete", "hoer*", "honkey", "Huevon", "hui", "injun", "jizz", "kanker*", "kike", "klootzak", "kraut", "knulle", "kuk", "kuksuger", "Kurac", "kurwa", "kusi*", "kyrpa*", "lesbo", "mamhoon", "masturbat*", "merd*", "mibun", "monkleigh", "mouliewop", "muie", "mulkku", "muschi", "nazis", "nepesaurio", "nigger*", "orospu", "paska*", "perse", "picka", "pierdol*", "pillu*", "pimmel", "piss*", "pizda", "poontsee", "poop", "porn", "prn", "prn", "preteen", "pula", "pule", "puta", "puto", "qahbeh", "queef*", "rautenberg", "schaffer", "scheiss*", "schlampe", "schmuck", "screw", "sh!t*", "sharmuta", "sharmute", "shipal", "shiz", "skribz", "skurwysyn", "sphencter", "spic", "spierdalaj", "splooge", "suka", "bb*", "testicle*", "titt*", "twat", "vittu", "wank*", "wetback*", "wichser", "wop*", "yed", "zabourah", "f u", "noob", "nood", "noobs", "feed", "feeder", "nerds", "player NA", "virgin", "uninstall", "sb", "fk" ];

LoLTH.Data.ItemCache = {"0":{"0":{"0":"1001","-48":"1033","-96":"1054","-144":"2009","-192":"2048","-240":"3007","-288":"3027","-336":"3046","-384":"3069","-432":"3083"},"-48":{"0":"1004","-48":"1036","-96":"1055","-144":"2010","-192":"2049","-240":"3008","-288":"3028","-336":"3047","-384":"3070","-432":"3084"},"-96":{"0":"1006","-48":"1037","-96":"1056","-144":"2037","-192":"2050","-240":"3009","-288":"3029","-336":"3048","-384":"3071","-432":"3085"},"-144":{"0":"1011","-48":"1038","-96":"1057","-144":"2039","-192":"2051","-240":"3010","-288":"3031","-336":"3050","-384":"3072","-432":"3086"},"-192":{"0":"1018","-48":"1039","-96":"1058","-144":"2040","-192":"2052","-240":"3020","-288":"3035","-336":"3056","-384":"3073","-432":"3087"},"-240":{"0":"1026","-48":"1042","-96":"1062","-144":"2041","-192":"3001","-240":"3022","-288":"3040","-336":"3057","-384":"3074","-432":"3089"},"-288":{"0":"1027","-48":"1043","-96":"1063","-144":"2043","-192":"3003","-240":"3023","-288":"3041","-336":"3060","-384":"3075","-432":"3090"},"-336":{"0":"1028","-48":"1051","-96":"1080","-144":"2044","-192":"3004","-240":"3024","-288":"3042","-336":"3065","-384":"3077","-432":"3091"},"-384":{"0":"1029","-48":"1052","-96":"2003","-144":"2045","-192":"3005","-240":"3025","-288":"3043","-336":"3067","-384":"3078","-432":"3092"},"-432":{"0":"1031","-48":"1053","-96":"2004","-144":"2047","-192":"3006","-240":"3026","-288":"3044","-336":"3068","-384":"3082","-432":"3093"}},"1":{"0":{"0":"3096","-48":"3110","-96":"3131","-144":"3145","-192":"3159","-240":"3175","-288":"3197","-336":"3252","-384":"3262","-432":"3272"},"-48":{"0":"3097","-48":"3111","-96":"3134","-144":"3146","-192":"3165","-240":"3180","-288":"3198","-336":"3253","-384":"3263","-432":"3273"},"-96":{"0":"3098","-48":"3112","-96":"3135","-144":"3151","-192":"3166","-240":"3181","-288":"3200","-336":"3254","-384":"3264","-432":"3274"},"-144":{"0":"3100","-48":"3115","-96":"3136","-144":"3152","-192":"3167","-240":"3184","-288":"3206","-336":"3255","-384":"3265","-432":"3275"},"-192":{"0":"3101","-48":"3116","-96":"3139","-144":"3153","-192":"3168","-240":"3185","-288":"3207","-336":"3256","-384":"3266","-432":"3276"},"-240":{"0":"3102","-48":"3117","-96":"3140","-144":"3154","-192":"3169","-240":"3187","-288":"3209","-336":"3257","-384":"3267","-432":"3277"},"-288":{"0":"3104","-48":"3122","-96":"3141","-144":"3155","-192":"3170","-240":"3188","-288":"3211","-336":"3258","-384":"3268","-432":"3278"},"-336":{"0":"3105","-48":"3123","-96":"3142","-144":"3156","-192":"3171","-240":"3190","-288":"3222","-336":"3259","-384":"3269","-432":"3279"},"-384":{"0":"3106","-48":"3124","-96":"3143","-144":"3157","-192":"3172","-240":"3191","-288":"3250","-336":"3260","-384":"3270","-432":"3280"},"-432":{"0":"3108","-48":"3128","-96":"3144","-144":"3158","-192":"3174","-240":"3196","-288":"3251","-336":"3261","-384":"3271","-432":"3281"}},"2":{"0":{"0":"3282","-48":"3350"},"-48":{"0":"3283","-48":"3351"},"-96":{"0":"3284","-48":"3352"},"-144":{"0":"3290","-48":"3361"},"-192":{"0":"3301","-48":"3362"},"-240":{"0":"3302","-48":"3363"},"-288":{"0":"3303","-48":"3364"},"-336":{"0":"3340","-48":"3401"},"-384":{"0":"3341"},"-432":{"0":"3342"}},"patch":"4.2.6"}

LoLTH.Data.ChampionCache = {"0":{"0":{"0":"Aatrox","-48":"Caitlyn","-96":"Ezreal"},"-48":{"0":"Ahri","-48":"Cassiopeia","-96":"FiddleSticks"},"-96":{"0":"Akali","-48":"Chogath","-96":"Fiora"},"-144":{"0":"Alistar","-48":"Corki","-96":"Fizz"},"-192":{"0":"Amumu","-48":"Darius","-96":"Galio"},"-240":{"0":"Anivia","-48":"Diana","-96":"Gangplank"},"-288":{"0":"Annie","-48":"Draven","-96":"Garen"},"-336":{"0":"Ashe","-48":"DrMundo","-96":"Gragas"},"-384":{"0":"Blitzcrank","-48":"Elise","-96":"Graves"},"-432":{"0":"Brand","-48":"Evelynn","-96":"Hecarim"}},"1":{"0":{"0":"Heimerdinger","-48":"Kayle","-96":"Lux"},"-48":{"0":"Irelia","-48":"Kennen","-96":"Malphite"},"-96":{"0":"Janna","-48":"Khazix","-96":"Malzahar"},"-144":{"0":"JarvanIV","-48":"KogMaw","-96":"Maokai"},"-192":{"0":"Jax","-48":"Leblanc","-96":"MasterYi"},"-240":{"0":"Jayce","-48":"LeeSin","-96":"MissFortune"},"-288":{"0":"Karma","-48":"Leona","-96":"MonkeyKing"},"-336":{"0":"Karthus","-48":"Lissandra","-96":"Mordekaiser"},"-384":{"0":"Kassadin","-48":"Lucian","-96":"Morgana"},"-432":{"0":"Katarina","-48":"Lulu","-96":"Nami"}},"2":{"0":{"0":"Nasus","-48":"Rammus","-96":"Singed"},"-48":{"0":"Nautilus","-48":"Renekton","-96":"Sion"},"-96":{"0":"Nidalee","-48":"Rengar","-96":"Sivir"},"-144":{"0":"Nocturne","-48":"Riven","-96":"Skarner"},"-192":{"0":"Nunu","-48":"Rumble","-96":"Sona"},"-240":{"0":"Olaf","-48":"Ryze","-96":"Soraka"},"-288":{"0":"Orianna","-48":"Sejuani","-96":"Swain"},"-336":{"0":"Pantheon","-48":"Shaco","-96":"Syndra"},"-384":{"0":"Poppy","-48":"Shen","-96":"Talon"},"-432":{"0":"Quinn","-48":"Shyvana","-96":"Taric"}},"3":{"0":{"0":"Teemo","-48":"Vayne","-96":"Zac"},"-240":{"0":"TwistedFate","-96":"Jinx","-48":"Volibear"},"-48":{"0":"Thresh","-48":"Veigar","-96":"Zed"},"-96":{"0":"Tristana","-48":"Vi","-96":"Ziggs"},"-144":{"0":"Trundle","-48":"Viktor","-96":"Zilean"},"-192":{"0":"Tryndamere","-48":"Vladimir","-96":"Zyra"},"-288":{"0":"Twitch","-48":"Warwick","-96":"Yasuo"},"-336":{"0":"Udyr","-48":"Xerath"},"-384":{"0":"Urgot","-48":"XinZhao"},"-432":{"0":"Varus","-48":"Yorick"}},"patch":"4.2.6"}

LoLTH.Data.SummonerCache = {"0":{"0":"SummonerBarrier","-48":"SummonerMana"},"-96":{"0":"SummonerBoost"},"-144":{"0":"SummonerClairvoyance"},"-192":{"0":"SummonerDot","-48":"SummonerRevive"},"-240":{"0":"SummonerExhaust","-48":"SummonerSmite"},"-288":{"0":"SummonerFlash","-48":"SummonerTeleport"},"-384":{"0":"SummonerHaste"},"-432":{"0":"SummonerHeal"},"-48":{"-48":"SummonerOdinGarrison"},"patch":"4.2.6"}

LoLTH.Utility.Round = function(num, idp) {
	return Math.round(num * Math.pow(10, idp)) / Math.pow(10, idp);
};

LoLTH.Utility.PatchCheck = function() {
	if (LoLTH.Data.ItemCache["patch"] != Riot.DDragon.useModel('item').version)  {
		return "<div class='LoLTHError'>Item Cache patch numer does not match current patch number. Please update Tribunal Helper <a href='https://code.google.com/p/tribunal-helper/'>here</a>.</div>";
	} 
	else {
		return "";
	}
}

LoLTH.Utility.ItemCheckWarning = function() {
	if (!LoLTH.Data.ItemChecks)  {
		return "<div class='LoLTHError'>Item Checks are currently disabled.</div>";
	} 
	else {
		return "";
	}
}


LoLTH.Utility.GetBaseItem = function(itemNumber) {
     var parentItem = itemNumber,
		baseItem = 0;
    if (itemNumber == undefined) { return 0 };
     do {
		baseItem = Riot.DDragon.useModel('item').get(parentItem).from[0];
		if (baseItem !== undefined) {
			parentItem = baseItem;
		}
	}
	while ( baseItem !== undefined ) 
	
	
	return parentItem;
}

LoLTH.Fetch.Summary = function() {
	LoLTH.Summary["Case Number"] = document.getElementsByClassName("raw-case-number")[0].innerHTML;
	LoLTH.Summary["Total Reports"] = document.getElementsByClassName("total-reports-fill")[0].innerHTML;
	LoLTH.Summary["Total Games"] = document.getElementsByClassName("total-games-fill")[0].innerHTML;
	LoLTH.Summary["Score"] = 0;
	LoLTH.Summary["Verdict"] = "Judge By Hand";
};

LoLTH.Fetch.GameData = function() {
	for (var i = 1; i <=  LoLTH.Summary["Total Games"] ; i++) {
		LoLTH.Game[i] = $('#game'+i);
	}
};

LoLTH.Fetch.ItemId = function(sprite, x, y) {
	if (LoLTH.Data.ItemCache[sprite] && LoLTH.Data.ItemCache[sprite][x] && LoLTH.Data.ItemCache[sprite][x][y] && typeof LoLTH.Data.ItemCache[sprite][x][y]) {
		return LoLTH.Data.ItemCache[sprite][x][y];
	}
	return false;
};

LoLTH.Fetch.Champion = function(sprite, x, y) {
        if (LoLTH.Data.ChampionCache[sprite] && LoLTH.Data.ChampionCache[sprite][x] && LoLTH.Data.ChampionCache[sprite][x][y] && typeof LoLTH.Data.ChampionCache[sprite][x][y] === "string") {
                var championName = LoLTH.Data.ChampionCache[sprite][x][y];
                championName = championName.toLowerCase();
                return championName;
        }
        return "";
};

LoLTH.Fetch.SpellId = function(x, y) {
	if (LoLTH.Data.SummonerCache[x] && LoLTH.Data.SummonerCache[x][y]) {
		return LoLTH.Data.SummonerCache[x][y];
	}
	return false;
}

LoLTH.Parse.GameData = function() {
	for (var i = 1; i <= LoLTH.Summary["Total Games"]; i++) {
		var gameData = $('#game'+i),
			kda,
			kdaParts;
		LoLTH.Game[i]["Outcome"] = gameData.find('#stat-outcome-fill').text();
		LoLTH.Game[i]["Game Length"] = gameData.find('#stat-length-fill').text();
		LoLTH.Game[i]["Mode"] = gameData.find('#stat-type-fill').text();
		kda = gameData.find('.reported-player .player-kda')[0].innerHTML;
		kdaParts = kda.split('/');
		LoLTH.Game[i]["Kills"] = kdaParts[0];
		LoLTH.Game[i]["Deaths"] = kdaParts[1];
		LoLTH.Game[i]["Assissts"] = kdaParts[2];
		LoLTH.Game[i].TotalScore = 0;
		// Item Parsing
		LoLTH.Game[i].Items = {};
		LoLTH.Parse.Items(gameData, i);
		// Report Parsing
		LoLTH.Game[i].reports = {};
		var reports = $('#game'+i).find(".report-reason");
		for (var j = 0; j < reports.length; j++) {
			var reportName = reports[j].innerHTML;
			var score = LoLTH.Scorer[reportName](gameData);
			console.log(reportName+": "+score);
			LoLTH.Game[i].reports[j] = [ reportName , score ];
			LoLTH.Game[i].TotalScore += score;
		}
		
		// Start Custom Scorers
		
		// Item Checks
		if (LoLTH.Data.ItemChecks) {
			// Mundo Shoe Store
			LoLTH.Game[i].reports[1001] = LoLTH.Scorer["Mundo Shoe Store"](i);
			LoLTH.Game[i].TotalScore += LoLTH.Game[i].reports[1001][1];
			console.log("Mundo Shoe Store: "+LoLTH.Game[i].reports[1001][1]);
		
			// Multi-Item Check
			LoLTH.Game[i].reports[2001] = LoLTH.Scorer["Multi Item Check"](i);
			LoLTH.Game[i].TotalScore += LoLTH.Game[i].reports[2001][1];
			console.log("Multi-Item Check Score:"+LoLTH.Game[i].reports[2001][1]);
		}
		// End Custom Scorers
		
		LoLTH.Game[i].TotalReports = reports.length;
		
		LoLTH.Game[i]["Score"] = LoLTH.Utility.Round( (LoLTH.Game[i].TotalScore / ( LoLTH.Game[i].TotalReports - ( LoLTH.Game[i].TotalReports * .1) ) ), 1);
		if ( LoLTH.Game[i]["Score"] > 10 ) { LoLTH.Game[i]["Score"] = 10 }
		
		LoLTH.Summary["Score"] += LoLTH.Game[i]["Score"];
	}
	LoLTH.Summary["Score"] = LoLTH.Utility.Round( ( LoLTH.Summary["Score"] / LoLTH.Summary["Total Games"] ), 1);
	LoLTH.Parse.Verdict();
};

LoLTH.Parse.Chat = {};

LoLTH.Parse.Chat.Profanity = function(message) {
	var pCount = 0;
	for (var i = 0;  i < LoLTH.Data.ProfanityList.length; i++) {
		if (message.contains(LoLTH.Data.ProfanityList[i])) {
			pCount = pCount + 1;
		}
	}
	return pCount;
};

LoLTH.Parse.Items = function(gameData, gameNumber) {

	var $items = gameData.find('.reported-player .player-items .dd-icon');
	LoLTH.Game[gameNumber].Items.count = 0;

	$items.each(function (k, v) {
		var $item = $(this),
		position = $item.css('background-position');
		var coords = position.split(" ");
		coords[0] = coords[0].replace("px",""); 
		coords[1] = coords[1].replace("px",""); 
		LoLTH.Game[gameNumber].Items[k] = LoLTH.Fetch.ItemId(coords[0], coords[1]);
        if (LoLTH.Game[gameNumber].Items[k] == false) {
            console.log("Error Retriving Item ID for Game "+gameNumber+" Item Slot "+k);
            LoLTH.Game[gameNumber].Items[k] = undefined;
        }
		LoLTH.Game[gameNumber].Items.count += 1;
	});


};

LoLTH.Parse.Verdict = function() {
	if ( LoLTH.Summary["Score"] > 5 ) {
		LoLTH.Summary["Verdict"] = "<span class=''>Punish <i class='fa fa-thumbs-down'></i></span>";
	}
	else if ( LoLTH.Summary["Score"] >=0 ) {
		LoLTH.Summary["Verdict"] = "<span class=''>Judge By Hand <i class='fa fa-question'></i></span>";
	}
	else {
		LoLTH.Summary["Verdict"] = "<span class=''>Pardon <i class='fa fa-thumbs-up'></i></span>";
	}
};

LoLTH.Parse.HighestGame = function() {
	var scores = {},
		maxGame,
		maxScore = -1;
	for(var i = 1; i <= LoLTH.Summary["Total Games"]; i++) {
		scores[i] = LoLTH.Game[i]["Score"];
	}
	for (var game in scores) {
		if (scores.hasOwnProperty(game)) {
			var score = scores[game]
			if (score > maxScore) {
				 maxGame = game
				maxScore = score
			}
		}
	}
	return [maxGame, maxScore];
}

LoLTH.Scorer["Verbal Abuse"] = function(gameData) {
	var score = 0,
	count = 0;
	gameData.find('.chat-message').each(function () {
		var $this = jQuery(this),
		$container = $this.parent('tr'),
		message = $this.text(),
		isReportedPlayer = $container.hasClass('reported-player');
		if (isReportedPlayer) {
			count = count + LoLTH.Parse.Chat.Profanity(message);
		}
	});
	score = LoLTH.Utility.Round((count/LoLTH.Data.ReportableOffenses["Verbal Abuse"]), 1);
	if ( score > 10 ) { score = 10; }
	return score;
};

LoLTH.Scorer["Intentional Feeding"] = function(gameData) {
	var score = 0,
		kills = 0,
		deaths = 0,
		assists = 0,
		kda, kdaParts, p;
	
	kda = gameData.find('.reported-player .player-kda')[0].innerHTML;
	kdaParts = kda.split('/');
	kills = kdaParts[0];
	deaths = kdaParts[1];
	assists = kdaParts[2];
	
	p = (kills + assists) / deaths
	score = p * LoLTH.Data.ReportableOffenses["Intentional Feeding"];
	
	if ( score > 10 ) { score = 10; }
	
	return score;
};

LoLTH.Scorer["Assisting Enemy Team"] = function(gameData) {
	var score = 3;
	return score;
};

LoLTH.Scorer["Refusing to Communicate"] = function(gameData) {
	var score = 3;
	return score;
};

LoLTH.Scorer["Inappropriate Name"] = function(gameData) {
	var score = 3;
	return score;
};

LoLTH.Scorer["AFK"] = function(gameData) {
	var score = 3;
	if ( gameData.find('#stat-outcome-fill').text() == "AFK" || gameData.find('#stat-outcome-fill').text() == "Leave") {
		score = 10;
	}
	return score;
};

LoLTH.Scorer["Negative Attitude"] = function(gameData) {
	var score = 0,
	count = 0;
	gameData.find('.chat-message').each(function () {
		var $this = jQuery(this),
		$container = $this.parent('tr'),
		message = $this.text(),
		isReportedPlayer = $container.hasClass('reported-player');
		if (isReportedPlayer) {
			count = count + LoLTH.Parse.Chat.Profanity(message);
		}
	});
	score = LoLTH.Utility.Round((count/LoLTH.Data.ReportableOffenses["Negative Attitude"]), 1);
	if ( score > 10 ) { score = 10; }
	return score;
};

LoLTH.Scorer["Spamming"] = function(gameData) {
	var score = 0,
		spammer = 0,
		spam = 0,
		threshold = 5,
		trigger = 3,
		timestamp,
		prevTimestamp;
	
	gameData.find('.chat-timestamp').each(function () {
		var $this = jQuery(this),
		$container = $this.parent('tr'),
		chatTimestamp = $this.text(),
		isReportedPlayer = $container.hasClass('reported-player');
		chatTimestamp = chatTimestamp.replace("[", "");
		chatTimestamp = chatTimestamp.replace("]", "");
		chatTimestamp = chatTimestamp.split(":");
		chatTimestamp = chatTimestamp[0]*3600+chatTimestamp[1]*60+chatTimestamp[2]*1;
		if (isReportedPlayer) {
			if (chatTimestamp - prevTimestamp < threshold) {
				spam = spam + 1
			} else if (spam > trigger) {
				spammer = spammer + 1;
				spam = 0;
			}
			prevTimestamp = chatTimestamp;
		}
	});
	
	score = score * LoLTH.Data.ReportableOffenses["Spamming"];
	
	if ( score > 10 ) { score = 10; }
	
	return score;
};

LoLTH.Scorer["Offensive Language"] = function(gameData) {
	var score = 0,
	count = 0;
	gameData.find('.chat-message').each(function () {
		var $this = jQuery(this),
		$container = $this.parent('tr'),
		message = $this.text(),
		isReportedPlayer = $container.hasClass('reported-player');
		if (isReportedPlayer) {
			count = count + LoLTH.Parse.Chat.Profanity(message);
		}
	});
	score = LoLTH.Utility.Round((count/LoLTH.Data.ReportableOffenses["Offensive Language"]), 1);
	if ( score > 10 ) { score = 10; }
	return score;
};

LoLTH.Scorer["Mundo Shoe Store"] = function(gameNumber) {
	var score = 0,
		bootCount = 0,
		baseItem = 0;
		
	for (var i = 0, length = LoLTH.Game[gameNumber].Items.count; i < length; i++) {
		baseItem = LoLTH.Utility.GetBaseItem(LoLTH.Game[gameNumber].Items[i]);
		if (baseItem == 1001) {
			bootCount = bootCount + 1;
		}
	}
	
	console.log("Boot Count:"+bootCount);
	if (bootCount > 1) {
		score = 10;
	}
	
	return ["Mundo Shoe Store" , score];
};

LoLTH.Scorer["Multi Item Check"] = function(gameNumber) {
	var score = 0,
		itemsDupe = LoLTH.Game[gameNumber].Items,
		itemCount = {};
	
	for (var i = 0, j = itemsDupe.count; i < j; i++) {
		itemCount[itemsDupe[i]] = (itemCount[itemsDupe[i]] || 0) + 1
	}
	
	// Whitelist Items
	// 1011 - Giant's Belt
	// 1038 - B.F. Sword
	// 1058 - Needlessly Large Rod
	
	var itemWhiteList = ["1011", "1038", "1058" ]
	
	for (var key in itemWhiteList) {
		itemCount[itemWhiteList[key]] = 0
	}
	console.log(itemCount);
	for (var key in itemCount) {
        if (key != "undefined") {
			if (itemCount.hasOwnProperty(key)) {
				var value = itemCount[key];
				if (value  > 2) {
					score = score + 3;
				} 
				else if (value  > 3) {
					score = score + 5;
				}
				else if (value  > 4) {
					score = score + 7;
				}
			}
        }
	}
	
	if ( score > 10 ) { score = 10; }
	
	return ["Multi Item Check", score];
};

// <div id='LoLTHAccord'><p class='LoLTHHeader'>Summary</p><div id='LoLTHSummary' class='LoLTHBlock'>Overall</div><p class='LoLTHHeader'>Game 1</p><div id='LoLTHGame1' class='LoLTHBlock'>Game 1 Summary</div><p class='LoLTHHeader'>Game 2</p><div id='LoLTHGame2' class='LoLTHBlock'>Game 2 Summary</div></div>

LoLTH.Output.Build = function() {
	var htmlOutput = "";
	htmlOutput += "<div id='LoLTHWrapper' class='LoLTHWrapper'><div align='left'>";
	htmlOutput += "<div id='LoLTHAccord'>";
	htmlOutput += "<header class='LoLTHHeader'>Summary</header><div id='LoLTHSummary' class='LoLTHBlock'>";
	htmlOutput += "Total Reports: "+LoLTH.Summary["Total Reports"]+"</br> Total Games: "+LoLTH.Summary["Total Games"]+"</br>";
	htmlOutput += "Highest Scoring Game: "+LoLTH.Parse.HighestGame().slice(0,1)+"  ("+LoLTH.Parse.HighestGame().slice(1)+")</br>";
	htmlOutput += "</br>";
	htmlOutput += "</div>";
	for (var i = 1; i <= LoLTH.Summary["Total Games"]; i++) {
		htmlOutput += "<header class='LoLTHHeader'>Game " + i + "</header><div id='LoLTHGame" + i +"' class='LoLTHBlock'>";
		htmlOutput += "Game Score: " + LoLTH.Game[i]["Score"] + "</br>";
		htmlOutput += "Game Mode: " + LoLTH.Game[i]["Mode"] + "</br>";
		htmlOutput += "Game Outcome: " + LoLTH.Game[i]["Outcome"] + "</br>Game Length: " + LoLTH.Game[i]["Game Length"] + "</br>";
		htmlOutput += "KDA: " +  LoLTH.Game[i]["Kills"] + "/" + LoLTH.Game[i]["Deaths"] + "/" + LoLTH.Game[i]["Assissts"] + "</br>";
		htmlOutput += "</br>";
		for (var j = 0; j < LoLTH.Game[i].TotalReports; j++) {
			htmlOutput += LoLTH.Game[i].reports[j][0] + ": " + LoLTH.Game[i].reports[j][1] + "</br>";
		}
		htmlOutput += "</br>";
		// Custom Scorer Output
		if (LoLTH.Data.ItemChecks) {
			if (LoLTH.Game[i].reports[1001][1] !== 0) {
				htmlOutput += "<span class='LoLTHPunish'>Multiple Boots Detected!</span></br>";
			}
			if (LoLTH.Game[i].reports[2001][1] !== 0) {
				htmlOutput += "<span class='LoLTHPunish'>Multiple Duplicate Items Detected!</span></br>";
			}
		}
		// End Custom Scorer Output
		htmlOutput += "</div>";
	}
	htmlOutput += LoLTH.Utility.PatchCheck();
	htmlOutput += LoLTH.Utility.ItemCheckWarning();
	htmlOutput += "</div>";
	return htmlOutput;
};

LoLTH.Output.Write = function(html) {

	$("#LoLTHTitle").html("<i class='fa fa-gavel'style='float: left'></i> Tribunal Helper: "+LoLTH.Summary["Score"]+" "+LoLTH.Summary["Verdict"]+"<i id='LoLTHArrowPointer'class='fa fa-chevron-down'style='float: right'></i>");
	
	$("#LoLTHController").append(html);

	$("#LoLTHAccord ").accordion({ 
		header: "header",
		active: 0,
		animate: "swing",
		collapsible: true,
		heightStyle: "content"
	});
	
var TOGGLEHANDLER = false;
$("#LoLTHTitle").click(function() {
		$("#LoLTHWrapper").toggle();
		
		if (TOGGLEHANDLER === false) {
			$("#LoLTHController").css({
				height: '350px'
			});
			TOGGLEHANDLER = true;
			$('#LoLTHArrowPointer').removeClass('fa-chevron-down').addClass('fa-chevron-up');
		}
		else if (TOGGLEHANDLER === true) {
			$("#LoLTHController").css({
				height: '20px'
			});
			TOGGLEHANDLER = false;
			$('#LoLTHArrowPointer').removeClass('fa-chevron-up').addClass('fa-chevron-down');
		}
		
		
});

	$("#LoLTHWrapper").css("background-color","none repeat scroll 0 0 #FFFFFF;");

};

LoLTH.TribunalRecess = function() {
	var recess = document.getElementById("finished_info_title");
	if (recess != undefined) {
		console.log("TRIBUNAL IN RECESS");
		return true;
	}
	return false;
}

LoLTH.TribunalLoaded = function() {
	LoLTH.AddItemTooltips();
	LoLTH.AddSummonerTooltips();
	LoLTH.AddChampionPortraitLinks();
	LoLTH.Run();
	console.log(LoLTH);
}

LoLTH.Output.Error = function(str) {
	var htmlOutput = "";
	htmlOutput += "<div id='LoLTHTitle' align='center'>Tribunal Helper</div>";
	htmlOutput += "<div id='LoLTHError' align='center'>" + str + "</div>";
	document.getElementById("LoLTHMini").innerHTML = htmlOutput;
	$('#LoLTHWrapper').css('height', '40px');
}

LoLTH.Run = function() {
	if (LoLTH.TribunalRecess() === false) {		
		LoLTH.Fetch.Summary();
		LoLTH.Fetch.GameData();
		LoLTH.Parse.GameData();
		LoLTH.Output.Write(LoLTH.Output.Build());
	}
}

if (LoLTH.TribunalRecess() === true) {
	LoLTH.Output.Error("Tribunal is in Recess");
}

// Fun Stuff

// Add Tooltips to Items
LoLTH.AddItemTooltips = function() {
	var items = $('.player-items .dd-icon');
	items.each(function (k, v) {
		var $item = $(this),
		position = $item.css('background-position');
		sprite = $item.css('background-image');
		sprite = sprite.replace(/"/g, "");
		//console.log(sprite);
		sprite = sprite[sprite.length-6];
		var coords = position.split(" ");
		coords[0] = coords[0].replace("px",""); 
		coords[1] = coords[1].replace("px",""); 
		var itemID = LoLTH.Fetch.ItemId(sprite, coords[0], coords[1]);
		$item.attr({
			"data-rg-id": itemID,
			"data-rg-name": "item"
		});
	});
}

// Add Tooltips to Summoner Spells
LoLTH.AddSummonerTooltips = function() {
	var spells = $('.player-summoner-spells .dd-icon');
	spells.each(function (k, v) {
		var $spell = $(this),
		position = $spell.css('background-position');
		var coords = position.split(" ");
		coords[0] = coords[0].replace("px",""); 
		coords[1] = coords[1].replace("px",""); 
		var itemID = LoLTH.Fetch.SpellId(coords[0], coords[1]);
		$spell.attr({
			"data-rg-id": itemID,
			"data-rg-name": "summoner"
		});
	});
}

// Add hyperlinks to Champion Portraits
LoLTH.AddChampionPortraitLinks = function() {
	var champs = $('.player-champion');
	champs.each(function (k, v) {
		var $champ = $(this).children(),
		position = $champ.css('background-position'),
		sprite = $champ.css('background-image');
		sprite = sprite.replace(/"/g, "");
		//console.log(sprite);
		sprite = sprite[sprite.length-6];
		var coords = position.split(" ");
		coords[0] = coords[0].replace("px",""); 
		coords[1] = coords[1].replace("px","");

		var hyperlink = "http://gameinfo.na.leagueoflegends.com/en/game-info/champions/"+ LoLTH.Fetch.Champion(sprite, coords[0], coords[1]);
		
		$champ.wrap("<a href='"+hyperlink+"'></a>");
	});
}

window.addEventListener('load', function () {
	window.setInterval(function() {
    	LoLTH.Fetch.Summary();  
    } ,1000);
	//  Loader
	console.log("Listener Added");
	var LoLTHLoader = window.setInterval(function() {
		var loadTest = $("#judger_overlay"+parseInt(LoLTH.Summary["Total Games"])).css("display");
		console.log("Interval Pulse - Load Test - "+loadTest);
		if ( loadTest === "none" ) {
			console.log("LoLTH: Loader Triggered!");
			LoLTH.TribunalLoaded();
			clearInterval(LoLTHLoader);
		}
	}, 500);
}, false);

// Polyfill String.prototype.contains
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/contains
// http://kangax.github.io/es5-compat-table/es6/#String.prototype.contains
if (!('contains' in String.prototype)) {
  String.prototype.contains = function(str, startIndex) {
    return -1 !== String.prototype.indexOf.call(this, str, startIndex);
  };
}

/*
    Copyright (C) 2014 

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/